#!/usr/bin/python
# -*- coding: utf-8 -*-

# Unit tests for comm_channels.py

import unittest
import threading
import comm_channels
import cPickle
import generic_mock
import random
import dispatcher

class TestTCPCommChannel(unittest.TestCase):
    
    def setUp(self):
        self.base_ = random.randint(10000,50000)        
        self.dispatcher_ = None
        self.dispatcher_addr = None
        self.hosts_ = {}

    def setDispatcher_(self, hosts):
        self.dispatcher_addr_ = ('127.0.0.1', self.base_)
        self.dispatcher_ = dispatcher.dispatcher(
            self.dispatcher_addr_, hosts)
        
    def setCommChannel(self, host_id, hosts):
        self.hosts_[host_id] = comm_channels.TCP_comm_channel(
            host_id, hosts, self.dispatcher_addr_) 

    def testConnectMessage(self):
        hosts = {1: ('127.0.0.1', self.base_ + 1),
                 2: ('127.0.0.1', self.base_ + 2)}
        ct = []
        dt = threading.Thread(target = self.setDispatcher_, args=[hosts])
        dt.start()
        for host_id in hosts:
            ct.append(threading.Thread(target = self.setCommChannel,
                                       args=[host_id, hosts]))
            ct[-1].start()
        for i in ct:
            i.join()
        dt.join()

if __name__ == '__main__':
    unittest.main()
